<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="######1). 字节码和.class文件区别新建Java对象时，JVM将这个对象对应的字节码加载到内存中，这个字节码的原始信息存放在classpath目录下（及Java工程的bin目录下）的.class文件中，类加载需要将.class文件导入硬盘，经过处理变成字节码加载到内存。">
<meta name="keywords" content="Android、iOS、Web、React Native">
<meta property="og:type" content="article">
<meta property="og:title" content="Java-类加载器">
<meta property="og:url" content="http://yoursite.com/blog/2018/08/06/Java-Advanced/Java-类加载器/index.html">
<meta property="og:site_name" content="凌浩雨_博客">
<meta property="og:description" content="######1). 字节码和.class文件区别新建Java对象时，JVM将这个对象对应的字节码加载到内存中，这个字节码的原始信息存放在classpath目录下（及Java工程的bin目录下）的.class文件中，类加载需要将.class文件导入硬盘，经过处理变成字节码加载到内存。">
<meta property="og:locale" content="default">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-d0c14c0f60ae2c4d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-ad24a9d9d33e93f4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-172fdfea813b82df.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-7892ebf9d0f303a6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-94ef3697d12c3291.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-bb81228074a23510.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-43ec71e12a19656d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-7298663fbbffb00e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-b8cae138c2e79cc5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-060e573f47e09919.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-08-06T10:45:17.276Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java-类加载器">
<meta name="twitter:description" content="######1). 字节码和.class文件区别新建Java对象时，JVM将这个对象对应的字节码加载到内存中，这个字节码的原始信息存放在classpath目录下（及Java工程的bin目录下）的.class文件中，类加载需要将.class文件导入硬盘，经过处理变成字节码加载到内存。">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/3110861-d0c14c0f60ae2c4d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/blog/2018/08/06/Java-Advanced/Java-类加载器/"/>





  <title>Java-类加载器 | 凌浩雨_博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">凌浩雨_博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/blog/blog/2018/08/06/Java-Advanced/Java-类加载器/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="凌浩雨">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="凌浩雨_博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Java-类加载器</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-08-06T18:01:39+08:00">
                2018-08-06
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>######1). 字节码和.class文件区别<br>新建Java对象时，JVM将这个对象对应的字节码加载到内存中，这个字节码的原始信息存放在classpath目录下（及Java工程的bin目录下）的.class文件中，类加载需要将.class文件导入硬盘，经过处理变成字节码加载到内存。<br><a id="more"></a></p>
<p>示例：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">public class ClassLoaderTest &#123;</span><br><span class="line">	public static void main(String[] args) &#123;</span><br><span class="line">		// 输出ClassLoaderTest的类加载器名称</span><br><span class="line">		System.out.println(&quot;ClassLoaderTest类的类加载器名称：&quot; + ClassLoaderTest.class.getClassLoader().getClass().getName());</span><br><span class="line">		System.out.println(&quot;System类的类加载器名称：&quot; + System.class.getClassLoader());</span><br><span class="line">		System.out.println(&quot;List类的类加载器名称：&quot; + List.class.getClassLoader());</span><br><span class="line">		</span><br><span class="line">		// 获取ClassLoaderTest类的类加载器</span><br><span class="line">		ClassLoader classLoader = ClassLoaderTest.class.getClassLoader();</span><br><span class="line">		while (null != classLoader) &#123;</span><br><span class="line">			System.out.println(classLoader.getClass().getName() + &quot;-&gt;&quot;);</span><br><span class="line">			// 获取类加载器的父类</span><br><span class="line">			classLoader = classLoader.getParent();</span><br><span class="line">		&#125;</span><br><span class="line">		System.out.println(classLoader);		</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-d0c14c0f60ae2c4d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图1.png"><br>从打印结果可以看出ClassLoaderTest类是有AppClassLoader加载的。<br>因为System类，List，Map等这样的系统提供jar类都在rt.jar中，所以由BootStrap类加载器加载，因为BootStrap是祖先类，不是Java编写的，所以打印出class为null。<strong>详情请看第三点：类加载器的委托机制</strong></p>
<p>######2). Java虚拟中的类加载器<br>Java虚拟机中可以安装多个类加载器，系统默认的有三个，每个类负责加载特定位置的类：<strong>BootStrap</strong>，<strong>ExtClassLoader</strong>，<strong>AppClassLoader</strong><br>由于类加载器本身是Java类，也需要被类加载器加载，因此必须有一个为类加载器不是Java类，因此Bootstrap是由C/C++代码编写，被封装到JVM内核中，ExtClassLoader和AppClassLoader是Java类。<br>类加载器属性结构图：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-ad24a9d9d33e93f4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图2.png"></p>
<p>######3). 类加载器的委托机制<br><strong>问题：</strong>Java虚拟机要加载第一个类的时候，使用哪一个类加载器加载？<br>(1). 当前线程的类加载器加载线程中的第一个类(当前线程的类加载器：Thread类中有一个get/setContextClassLoader(ClassLoader);方法，可以获取/指定本线程中的类加载器)<br>(2). 如果类A引用了类B，Java虚拟机将使用加载类A的加载器来加载类B<br>(3). 可以直接调用ClassLoader.loadClass(String className)方法来指定某个类加载器去加载某个类</p>
<p>每个类加载器加载类时，先委托其上级类加载器来加载，当所有父加载器没有加载到类时，回到发起者类加载器，如果还是加载不了，则会抛出ClassNotFoundException。</p>
<p><strong>好处：</strong><br>能够很好的统一管理类加载，首先交给上级，如果上级有，就加载，这样如果之前已经加载过的类，这时候在来加载它的时候只要拿过来用就可以了，无需二次加载</p>
<p>######4). 测试ExtClassLoader</p>
<ul>
<li>将ClassLoaderTest类打包为Jar文件，拷贝至<code>jdk\jre\lib\ext\下</code>路径<br><img src="https://upload-images.jianshu.io/upload_images/3110861-172fdfea813b82df.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图3.png"></li>
<li>接下来在eclipse中运行ClassLoaderTest文件，其打印结果为<br><img src="https://upload-images.jianshu.io/upload_images/3110861-7892ebf9d0f303a6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图4.png"><br>打印结果验证了类加载器的委托机制.<br><strong>测试完成后记得将test.jar删除</strong></li>
</ul>
<p>######5). 类加载器主要方法</p>
<ul>
<li>默认的类加载器<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">System.out.println(&quot;默认的类加载器:&quot;+ClassLoader.getSystemClassLoader());</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p><img src="https://upload-images.jianshu.io/upload_images/3110861-94ef3697d12c3291.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图5.png"></p>
<ul>
<li><p>loadClass(String name) 源码</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line">public Class&lt;?&gt; loadClass(String name) throws ClassNotFoundException &#123;</span><br><span class="line">    return loadClass(name, false);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">protected Class&lt;?&gt; loadClass(String name, boolean resolve) throws ClassNotFoundException</span><br><span class="line">&#123;</span><br><span class="line">    //  加锁，进行同步处理，可能多个线程加载类</span><br><span class="line">    synchronized (getClassLoadingLock(name)) &#123;</span><br><span class="line">        // 检查是否已经加载过</span><br><span class="line">        Class&lt;?&gt; c = findLoadedClass(name);</span><br><span class="line">        if (c == null) &#123;</span><br><span class="line">            long t0 = System.nanoTime();</span><br><span class="line">            try &#123;</span><br><span class="line">                // 如果自定义的类加载器的parent不为null,就调用parent的loadClass进行类加载</span><br><span class="line">                if (parent != null) &#123;</span><br><span class="line">                    c = parent.loadClass(name, false);</span><br><span class="line">                &#125; else &#123;</span><br><span class="line">                    // 如果自定义的类加载器的parent为null，就调用findBootstrapClassOrNull方法查找类，就是BootStrap类加载器</span><br><span class="line">                    c = findBootstrapClassOrNull(name);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; catch (ClassNotFoundException e) &#123;</span><br><span class="line">                // 类未发现异常</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            if (c == null) &#123;</span><br><span class="line">                // 如果仍然没有发现，就调用自己的findClass方法进行进行类加载</span><br><span class="line">                long t1 = System.nanoTime();</span><br><span class="line">                c = findClass(name);</span><br><span class="line"></span><br><span class="line">                // this is the defining class loader; record the stats</span><br><span class="line">                sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);</span><br><span class="line">                sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);</span><br><span class="line">                sun.misc.PerfCounter.getFindClasses().increment();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        if (resolve) &#123;</span><br><span class="line">            resolveClass(c);</span><br><span class="line">        &#125;</span><br><span class="line">        return c;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>defineClass，将class文件的字节数组编译成一个class对象，不能重写，内部实现为C/C++代码<br><img src="https://upload-images.jianshu.io/upload_images/3110861-bb81228074a23510.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图6.png"></p>
</li>
</ul>
<p>######6). 自定义ClassLoader</p>
<ul>
<li><p>定义一个被加载的类</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 加载类</span><br><span class="line"> * @author mazaiting</span><br><span class="line"> */</span><br><span class="line">public class ClassLoaderAttachment extends Date&#123;</span><br><span class="line">	private static final long serialVersionUID = -1892974244318329380L;</span><br><span class="line">	</span><br><span class="line">	@Override</span><br><span class="line">	public String toString() &#123;</span><br><span class="line">		return &quot;Hello ClassLoader&quot;;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>自定义ClassLoader</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 自定义类加载器</span><br><span class="line"> * 步骤：</span><br><span class="line"> * 	1. 继承ClasssLoader</span><br><span class="line"> * 	2. 重写findClass(String name) 方法</span><br><span class="line"> * @author mazaiting</span><br><span class="line"> */</span><br><span class="line">public class MyClassLoader extends ClassLoader&#123;</span><br><span class="line">	/**需要加载类.class文件的目录*/</span><br><span class="line">	private String classDir;</span><br><span class="line">	/**无参构造*/</span><br><span class="line">	public MyClassLoader() &#123;&#125;</span><br><span class="line">	public MyClassLoader(String classDir) &#123;</span><br><span class="line">		this.classDir = classDir;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	// 测试，先将ClassLoaderAttachment.class文件加密到工程的class_temp目录下</span><br><span class="line">	public static void main(String[] args) throws Exception &#123;</span><br><span class="line">		// 配置运行参数</span><br><span class="line">		// ClassLoaderAttachment.class原路径--E:\test\java_advanced\ClassLoader\bin\com\mazaiting\ClassLoaderAttachment.class </span><br><span class="line">		String srcPath = args[0];</span><br><span class="line">		// ClassLoaderAttachment.class输出路径--E:\test\java_advanced\ClassLoader\class_temp\</span><br><span class="line">		String desPath = args[1];</span><br><span class="line">		// 获取文件名</span><br><span class="line">		String desFileName = srcPath.substring(srcPath.lastIndexOf(&quot;\\&quot;) +1);</span><br><span class="line">		// 配置目标文件路径</span><br><span class="line">		String desPathFile = desPath + &quot;/&quot; + desFileName;</span><br><span class="line">		FileInputStream fis = new FileInputStream(srcPath);</span><br><span class="line">		FileOutputStream fos = new FileOutputStream(desPathFile);</span><br><span class="line">		// 将class进行加密</span><br><span class="line">		encodeAndDecode(fis, fos);</span><br><span class="line">		fis.close();</span><br><span class="line">		fos.close();</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	@Override</span><br><span class="line">	protected Class&lt;?&gt; findClass(String name) throws ClassNotFoundException &#123;</span><br><span class="line">		// class文件的路径</span><br><span class="line">		String classPathFile = classDir + &quot;/&quot; + name + &quot;.class&quot;;</span><br><span class="line">		try &#123;</span><br><span class="line">			// 将class文件进行解密</span><br><span class="line">			FileInputStream fis = new FileInputStream(classPathFile);</span><br><span class="line">			ByteArrayOutputStream baos = new ByteArrayOutputStream();</span><br><span class="line">			encodeAndDecode(fis, baos);</span><br><span class="line">			byte[] classByte = baos.toByteArray();</span><br><span class="line">			// 将字节流变成一个class</span><br><span class="line">			return defineClass(null, classByte, 0, classByte.length);</span><br><span class="line">		&#125; catch (Exception e) &#123;</span><br><span class="line">			e.printStackTrace();</span><br><span class="line">		&#125;</span><br><span class="line">		</span><br><span class="line">		return super.findClass(name);</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	/**</span><br><span class="line">	 * 加密解密</span><br><span class="line">	 * @param is 输入流</span><br><span class="line">	 * @param os 输出流</span><br><span class="line">	 * @throws IOException </span><br><span class="line">	 */</span><br><span class="line">	private static void encodeAndDecode(InputStream is, OutputStream os) throws IOException &#123;</span><br><span class="line">		int len;</span><br><span class="line">		while ((len = is.read()) != -1) &#123;</span><br><span class="line">			len ^= 0xFF;</span><br><span class="line">			os.write(len);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>运行：在MyClassLoader的main方法右键 -&gt; Run As -&gt; Run Configurations…，进行如下配置(配置前请确保ClassLoader工程目录下存在class_temp文件夹，其中第一个参数是ClassLoaderAttachment.class文件的源路径，第二个参数是加密后存放的目录)，点击Run运行，此时在<code>E:\test\java_advanced\ClassLoader\class_temp</code>将会生成加密后的<code>ClassLoaderAttachment.class</code>文件<br><img src="https://upload-images.jianshu.io/upload_images/3110861-43ec71e12a19656d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图7.png"></p>
</li>
<li>使用，在<code>ClassLoaderTest</code>的main函数中应用<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">public class ClassLoaderTest &#123;</span><br><span class="line">	public static void main(String[] args) &#123;</span><br><span class="line">		try &#123;</span><br><span class="line">			// 加载类</span><br><span class="line">			Class classDate = new MyClassLoader(&quot;class_temp&quot;).loadClass(&quot;ClassLoaderAttachment&quot;);</span><br><span class="line">			// 创建实例</span><br><span class="line">			Date date = (Date) classDate.newInstance();</span><br><span class="line">			// 输出ClassLoaderAttachment类的加载器名称</span><br><span class="line">			System.out.println(&quot;ClassLoader: &quot; + date.getClass().getClassLoader().getClass().getName());</span><br><span class="line">			// 调用方法</span><br><span class="line">			System.out.println(date.toString());</span><br><span class="line">		&#125; catch (Exception e) &#123;</span><br><span class="line">			e.printStackTrace();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-7298663fbbffb00e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图8.png"></p>
<ul>
<li>如果loadClass方法的参数为类的全路径名<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">// 加载类</span><br><span class="line">Class classDate = new MyClassLoader(&quot;class_temp&quot;).loadClass(&quot;com.mazaiting.ClassLoaderAttachment&quot;);</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p><img src="https://upload-images.jianshu.io/upload_images/3110861-b8cae138c2e79cc5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图9.png"></p>
<ul>
<li>将<code>\class_temp\</code>路径下的ClassLoaderAttachment.class复制到<code>\bin\com\mazaiting\</code>路径下，然后运行<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Exception in thread &quot;main&quot; java.lang.ClassFormatError: Incompatible magic value 889275713 in class file com/mazaiting/ClassLoaderAttachment</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p><img src="https://upload-images.jianshu.io/upload_images/3110861-060e573f47e09919.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图10.png"><br><strong>不合适的魔数错误(class文件的前六个字节是个魔数用来标识class文件的)，因为加密后的数据AppClasssLoader无法解析。</strong></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/08/06/Java-Advanced/Java-泛型/" rel="next" title="Java-泛型">
                <i class="fa fa-chevron-left"></i> Java-泛型
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/08/06/Java-Design-Pattern/Java-Abstract-Factory-Pattern(抽象工厂模式)/" rel="prev" title="Java-Abstract-Factory-Pattern(抽象工厂模式)">
                Java-Abstract-Factory-Pattern(抽象工厂模式) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpeg"
                alt="凌浩雨" />
            
              <p class="site-author-name" itemprop="name">凌浩雨</p>
              <p class="site-description motion-element" itemprop="description">专业从事于移动端开发，Android与iOS均有涉及，主做Android开发与React Native开发</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">393</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">凌浩雨</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
